import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Tabs, Table, Tag, Button, Space, Statistic, Progress, Modal, Form, Input, Select, message } from 'antd';
import { 
  DashboardOutlined, 
  CloudOutlined, 
  FireOutlined, 
  ClearOutlined,
  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';

const { TabPane } = Tabs;
const { Option } = Select;

// 暖通空调设备数据接口
interface HVACDevice {
  id: string;
  name: string;
  type: 'AHU' | 'FCU' | 'VAV' | 'CHILLER' | 'BOILER' | 'PUMP';
  location: string;
  zone: string;
  status: 'running' | 'stopped' | 'maintenance' | 'fault';
  temperature: {
    current: number;
    setpoint: number;
    unit: '°C';
  };
  humidity: {
    current: number;
    setpoint: number;
    unit: '%';
  };
  airflow: {
    current: number;
    rated: number;
    unit: 'm³/h';
  };
  power: {
    current: number;
    rated: number;
    unit: 'kW';
  };
  efficiency: number;
  lastMaintenance: string;
  nextMaintenance: string;
  alarms: string[];
}

// 模拟暖通空调设备数据
const mockHVACDevices: HVACDevice[] = [
  {
    id: 'AHU-001',
    name: '空气处理机组-1',
    type: 'AHU',
    location: 'A栋1层',
    zone: '办公区域',
    status: 'running',
    temperature: { current: 22.5, setpoint: 23.0, unit: '°C' },
    humidity: { current: 45, setpoint: 50, unit: '%' },
    airflow: { current: 8500, rated: 10000, unit: 'm³/h' },
    power: { current: 15.2, rated: 18.5, unit: 'kW' },
    efficiency: 85,
    lastMaintenance: '2024-01-15',
    nextMaintenance: '2024-04-15',
    alarms: []
  },
  {
    id: 'FCU-002',
    name: '风机盘管-2',
    type: 'FCU',
    location: 'B栋2层',
    zone: '会议室',
    status: 'running',
    temperature: { current: 24.0, setpoint: 24.0, unit: '°C' },
    humidity: { current: 48, setpoint: 50, unit: '%' },
    airflow: { current: 1200, rated: 1500, unit: 'm³/h' },
    power: { current: 2.8, rated: 3.5, unit: 'kW' },
    efficiency: 92,
    lastMaintenance: '2024-01-20',
    nextMaintenance: '2024-04-20',
    alarms: []
  },
  {
    id: 'CHILLER-001',
    name: '冷水机组-1',
    type: 'CHILLER',
    location: '地下室',
    zone: '设备机房',
    status: 'fault',
    temperature: { current: 7.2, setpoint: 7.0, unit: '°C' },
    humidity: { current: 65, setpoint: 60, unit: '%' },
    airflow: { current: 0, rated: 0, unit: 'm³/h' },
    power: { current: 0, rated: 120, unit: 'kW' },
    efficiency: 0,
    lastMaintenance: '2024-01-10',
    nextMaintenance: '2024-04-10',
    alarms: ['压缩机故障', '冷媒泄漏']
  },
  {
    id: 'VAV-003',
    name: '变风量末端-3',
    type: 'VAV',
    location: 'C栋3层',
    zone: '开放办公区',
    status: 'running',
    temperature: { current: 23.5, setpoint: 23.0, unit: '°C' },
    humidity: { current: 47, setpoint: 50, unit: '%' },
    airflow: { current: 2800, rated: 3500, unit: 'm³/h' },
    power: { current: 1.2, rated: 1.8, unit: 'kW' },
    efficiency: 88,
    lastMaintenance: '2024-01-25',
    nextMaintenance: '2024-04-25',
    alarms: []
  },
  {
    id: 'PUMP-001',
    name: '冷冻水泵-1',
    type: 'PUMP',
    location: '地下室',
    zone: '设备机房',
    status: 'maintenance',
    temperature: { current: 12.0, setpoint: 12.0, unit: '°C' },
    humidity: { current: 70, setpoint: 60, unit: '%' },
    airflow: { current: 0, rated: 0, unit: 'm³/h' },
    power: { current: 0, rated: 22, unit: 'kW' },
    efficiency: 0,
    lastMaintenance: '2024-02-01',
    nextMaintenance: '2024-05-01',
    alarms: []
  }
];

const HVACSystem: React.FC = () => {
  const [devices, setDevices] = useState<HVACDevice[]>(mockHVACDevices);
  const [activeTab, setActiveTab] = useState('map');
  const [selectedDevice, setSelectedDevice] = useState<HVACDevice | null>(null);
  const [controlModalVisible, setControlModalVisible] = useState(false);
  const [form] = Form.useForm();

  // 计算统计数据
  const getStatistics = () => {
    const total = devices.length;
    const running = devices.filter(d => d.status === 'running').length;
    const fault = devices.filter(d => d.status === 'fault').length;
    const maintenance = devices.filter(d => d.status === 'maintenance').length;
    const totalPower = devices.reduce((sum, d) => sum + d.power.current, 0);
    const avgEfficiency = devices.reduce((sum, d) => sum + d.efficiency, 0) / total;
    
    return { total, running, fault, maintenance, totalPower, avgEfficiency };
  };

  const stats = getStatistics();

  // 获取状态配置
  const getStatusConfig = (status: string) => {
    const configs = {
      running: { color: 'success', icon: <PlayCircleOutlined />, text: '运行中' },
      stopped: { color: 'default', icon: <PauseCircleOutlined />, text: '已停止' },
      maintenance: { color: 'warning', icon: <ClockCircleOutlined />, text: '维护中' },
      fault: { color: 'error', icon: <WarningOutlined />, text: '故障' }
    };
    return configs[status as keyof typeof configs] || configs.stopped;
  };

  // 获取设备类型配置
  const getDeviceTypeConfig = (type: string) => {
    const configs = {
      AHU: { name: '空气处理机组', icon: <CloudOutlined /> },
      FCU: { name: '风机盘管', icon: <CloudOutlined /> },
      VAV: { name: '变风量末端', icon: <CloudOutlined /> },
      CHILLER: { name: '冷水机组', icon: <ClearOutlined /> },
      BOILER: { name: '锅炉', icon: <FireOutlined /> },
      PUMP: { name: '水泵', icon: <CloudOutlined /> }
    };
    return configs[type as keyof typeof configs] || { name: type, icon: <SettingOutlined /> };
  };

  // 设备控制
  const handleDeviceControl = (device: HVACDevice) => {
    setSelectedDevice(device);
    form.setFieldsValue({
      temperature: device.temperature.setpoint,
      humidity: device.humidity.setpoint,
      airflow: device.airflow.current
    });
    setControlModalVisible(true);
  };

  const handleControlSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (selectedDevice) {
        const updatedDevices = devices.map(device => {
          if (device.id === selectedDevice.id) {
            return {
              ...device,
              temperature: { ...device.temperature, setpoint: values.temperature },
              humidity: { ...device.humidity, setpoint: values.humidity },
              airflow: { ...device.airflow, current: values.airflow }
            };
          }
          return device;
        });
        setDevices(updatedDevices);
        message.success('设备参数设置成功');
        setControlModalVisible(false);
      }
    } catch (error) {
      console.error('设置失败:', error);
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: HVACDevice) => (
        <Space>
          {getDeviceTypeConfig(record.type).icon}
          <span>{text}</span>
        </Space>
      )
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => getDeviceTypeConfig(type).name
    },
    {
      title: '位置',
      dataIndex: 'location',
      key: 'location'
    },
    {
      title: '区域',
      dataIndex: 'zone',
      key: 'zone'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const config = getStatusConfig(status);
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      }
    },
    {
      title: '温度',
      key: 'temperature',
      render: (record: HVACDevice) => (
        <Space direction="vertical" size="small">
          <span>当前: {record.temperature.current}{record.temperature.unit}</span>
          <span>设定: {record.temperature.setpoint}{record.temperature.unit}</span>
        </Space>
      )
    },
    {
      title: '湿度',
      key: 'humidity',
      render: (record: HVACDevice) => (
        <Space direction="vertical" size="small">
          <span>当前: {record.humidity.current}{record.humidity.unit}</span>
          <span>设定: {record.humidity.setpoint}{record.humidity.unit}</span>
        </Space>
      )
    },
    {
      title: '功率',
      key: 'power',
      render: (record: HVACDevice) => (
        <Space direction="vertical" size="small">
          <span>{record.power.current}{record.power.unit}</span>
          <Progress 
            percent={Math.round((record.power.current / record.power.rated) * 100)} 
            size="small"
            status={record.status === 'fault' ? 'exception' : 'normal'}
          />
        </Space>
      )
    },
    {
      title: '效率',
      dataIndex: 'efficiency',
      key: 'efficiency',
      render: (efficiency: number) => (
        <Progress 
          percent={efficiency} 
          size="small"
          status={efficiency < 70 ? 'exception' : efficiency < 85 ? 'active' : 'success'}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (record: HVACDevice) => (
        <Space>
          <Button 
            type="primary" 
            size="small" 
            icon={<SettingOutlined />}
            onClick={() => handleDeviceControl(record)}
            disabled={record.status === 'fault'}
          >
            控制
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="设备总数"
              value={stats.total}
              prefix={<SettingOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="运行设备"
              value={stats.running}
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="故障设备"
              value={stats.fault}
              valueStyle={{ color: '#cf1322' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="维护设备"
              value={stats.maintenance}
              valueStyle={{ color: '#d48806' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="总功耗"
              value={stats.totalPower}
              precision={1}
              suffix="kW"
              prefix={<DashboardOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="平均效率"
              value={stats.avgEfficiency}
              precision={1}
              suffix="%"
              valueStyle={{ color: stats.avgEfficiency >= 85 ? '#3f8600' : '#d48806' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="电子地图" key="map">
            <div style={{ 
              height: '500px', 
              background: '#f0f2f5', 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              border: '1px dashed #d9d9d9',
              borderRadius: '6px'
            }}>
              <div style={{ textAlign: 'center', color: '#999' }}>
                <CloudOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                <div>暖通空调系统电子地图</div>
                <div style={{ fontSize: '12px', marginTop: '8px' }}>
                  显示各区域HVAC设备分布和运行状态
                </div>
              </div>
            </div>
          </TabPane>
          <TabPane tab="设备清单" key="equipment">
            <Table
              columns={columns}
              dataSource={devices}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
              scroll={{ x: 1200 }}
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 设备控制模态框 */}
      <Modal
        title={`控制设备: ${selectedDevice?.name}`}
        open={controlModalVisible}
        onOk={handleControlSubmit}
        onCancel={() => setControlModalVisible(false)}
        width={600}
      >
        {selectedDevice && (
          <Form form={form} layout="vertical">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="设定温度 (°C)"
                  name="temperature"
                  rules={[{ required: true, message: '请输入设定温度' }]}
                >
                  <Input type="number" min={16} max={30} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="设定湿度 (%)"
                  name="humidity"
                  rules={[{ required: true, message: '请输入设定湿度' }]}
                >
                  <Input type="number" min={30} max={70} />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="风量 (m³/h)"
                  name="airflow"
                  rules={[{ required: true, message: '请输入风量' }]}
                >
                  <Input type="number" min={0} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="运行模式" name="mode">
                  <Select placeholder="选择运行模式">
                    <Option value="auto">自动模式</Option>
                    <Option value="cooling">制冷模式</Option>
                    <Option value="heating">制热模式</Option>
                    <Option value="ventilation">通风模式</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            
            <Card title="当前状态" size="small" style={{ marginTop: '16px' }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Statistic
                    title="当前温度"
                    value={selectedDevice.temperature.current}
                    suffix="°C"
                    precision={1}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="当前湿度"
                    value={selectedDevice.humidity.current}
                    suffix="%"
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="当前功率"
                    value={selectedDevice.power.current}
                    suffix="kW"
                    precision={1}
                  />
                </Col>
              </Row>
            </Card>

            {selectedDevice.alarms.length > 0 && (
              <Card title="告警信息" size="small" style={{ marginTop: '16px' }}>
                {selectedDevice.alarms.map((alarm, index) => (
                  <Tag key={index} color="error" style={{ marginBottom: '8px' }}>
                    <WarningOutlined /> {alarm}
                  </Tag>
                ))}
              </Card>
            )}
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default HVACSystem;